import React, { useState, useEffect } from 'react';
import Taro, { usePageScroll } from '@tarojs/taro';
import { View, Image } from '@tarojs/components';
import { getSizeByScale } from '@/utils';
import pToTop from '@/images/common/toTop.png';

import './index.scss';

/*
功能：页面滚动距离顶部超过设定值后显示返回顶部按钮，点击按钮滚动到页面顶部
@top: 设计图上图标距离顶部的距离
*/
const ToTop = ({ top = 1000, scrollTop = null, handleToTopScrollView = null }) => {
  const [isDisplay, setIsDisplay] = useState(false);

  const handleToTop = () => {
    if (handleToTopScrollView) {
      handleToTopScrollView();
    } else {
      Taro.pageScrollTo({ scrollTop: Math.random() });
    }
  };

  const checkPosition = (curScrollTop) => {
    if (curScrollTop >= getSizeByScale(top)) {
      !isDisplay && setIsDisplay(true);
    } else {
      isDisplay && setIsDisplay(false);
    }
  };

  useEffect(() => {
    scrollTop !== null && checkPosition(scrollTop);
  }, [scrollTop]);

  usePageScroll((e) => {
    scrollTop === null && checkPosition(e.scrollTop);
  });

  return (
    <View
      className={
        'toTopContent' + (isDisplay ? ' showTop' : '') + (Taro.$isIphoneX ? ' highBottom' : '')
      }
    >
      <Image className="topImg" src={pToTop} onClick={handleToTop} />
    </View>
  );
};

export default ToTop;
